package com.ccb.ic.bbs.controller;

import com.ccb.ic.bbs.enums.CommentTypeEnum;
import com.ccb.ic.bbs.exception.CustomizeErrorCode;
import com.ccb.ic.query.bbs.CommentCreateDTO;
import com.ccb.ic.query.bbs.CommentDTO;
import com.ccb.ic.query.bbs.ResultDTO;
import com.ccb.ic.bbs.provider.UserProvider;
import com.ccb.ic.bbs.service.CommentService;
import com.ccb.ic.domain.bbs.Comment;
import com.ccb.ic.domain.bbs.User;
import com.ccb.ic.domain.bbs.UserAccount;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@RestController
public class CommentController {

    @Autowired
    private CommentService commentService;
    @Autowired
    UserProvider userProvider;

    @ResponseBody//@ResponseBody返回json格式的数据
    @RequestMapping(value = "/bbs/comment", method = RequestMethod.POST)
    public Object post(@RequestBody CommentCreateDTO commentCreateDTO,//@RequestBody接受json格式的数据
                       HttpServletRequest request) {
        User user = userProvider.getUser("token");
        UserAccount userAccount = userProvider.getUserAccount(user);
        if (user == null) {
            return ResultDTO.errorOf(CustomizeErrorCode.NO_LOGIN);
        }

        if (commentCreateDTO == null || StringUtils.isBlank(commentCreateDTO.getContent())) {
            return ResultDTO.errorOf(CustomizeErrorCode.CONTENT_IS_EMPTY);
        }

        Comment comment = new Comment();
        comment.setParentId(commentCreateDTO.getParentId());
        comment.setContent(commentCreateDTO.getContent());
        comment.setType(commentCreateDTO.getType());
        comment.setGmtModified(new Date());
        comment.setGmtCreate(new Date());
        comment.setCommentator(user.getId());
        comment.setLikeCount(0L);
        commentService.insert(comment,user,userAccount);

       return ResultDTO.okOf("回复成功！");

    }


    @ResponseBody
    @RequestMapping(value = "/bbs/comment/{id}", method = RequestMethod.GET)
    public ResultDTO<List<CommentDTO>> comments(@PathVariable(name = "id") Long id) {
        List<CommentDTO> commentDTOS = commentService.listByTargetId(id, CommentTypeEnum.COMMENT);
        return ResultDTO.okOf(commentDTOS);
    }
}
